<template>
	<div class="dangAncp-page-content px-2">	
		<div class="tip-box">
			<div v-if="!loading && !my_tags.length" class="text-center py-8 bg-gray-100 rounded">暂无档案数据</div>
			<div v-else-if="loading" class="text-center py-8 bg-gray-100 rounded">
				<a-spin tip="加载中..." />
			</div>
		</div>

		<div class="tag-box" v-for="tag, tag_index in my_tags" :key="`tag-${tag_index}`">
			<div class="tag-title card shadow-lg" :data-tag-name="tag.name">{{ tag.name }}</div>
			<div class="api-box">
				<!-- 这里遍历每个API -->
				<div
					class="api-item"
					v-for="path_data,path in tag.paths"
					:key="`api-${path}`"
					@click="current_active_path = (path as string)"
				>
					<div
						class="operation-item card shadow"
						:class="{ active: current_active_path == path }"
						v-for="(operation,operation_method) in path_data"
						:key="`operation-${operation_method}`"
						:data-path="path"
					>
						<div class="title">{{ (operation as Operation).summary }}						
						<a-tag								
								class="cursor-pointer mx-2 px-4 py-2"
								color="#40a9ff"
								@click="delItemTag(operation)"
							>删 除</a-tag>						
						</div>
						<div class="description py-2 px-2" v-if="(operation as Operation).description">
							<div v-for="it,index in (operation as any).description.split('<br/>')" :key="index">{{ it }}</div>
						</div>
						
						<div class="path-box flex-box overflow-x-auto">
							<div class="path copy-path flex-1 flex-box">
								<a-tag color="#87d068">良 好</a-tag>
								<a-tag								
								class="cursor-pointer mx-2 px-4 py-2"
								color="#40a9ff"
								@click="addItemEvent(path, operation_method, operation)"
							>添加事件</a-tag>
								<!--
								<div class="flex-1">{{ path }}</div>
								-->
							</div>
						</div>						
						<a-table
							v-if="(operation as Operation).parameters && (operation as any).parameters.length"
							:dataSource="(operation as Operation).parameters"
							bordered
							size="small"
							:pagination="false"
							:scroll="{ x: 'max-content' }"
							@resizeColumn="(w, col) => col.width = w"
						>
							<a-table-column key="name" title="事件名称" :width="100">
								<template #default="{ record }">
									<div
										class="param-name copy-param cursor-pointer"
										:data-name="record.name"
									>{{ record.name }}</div>
								</template>
							</a-table-column>
							<a-table-column key="schema" title="时间" :width="100">
								<template #default="{ record }">{{ record.schema && record.schema.type }}</template>
							</a-table-column>
							<!--
							<a-table-column key="required" title="默认值" :width="160">
								<template #default="{ record }">
									<a-tag v-if="record.required" color="green">必须</a-tag>
									<div v-else>{{ record.example }}</div>
								</template>
							</a-table-column>
							-->
							<a-table-column key="in" title="关联档案" data-index="in" :width="110" />
							
							<a-table-column key="schema" title="联系人" :width="70">
								<template #default="{ record }">{{ record.schema && record.schema.pattern }}</template>
							</a-table-column>
							
							<a-table-column key="schema" title="电话" :width="80">
								<template #default="{ record }">{{ record.schema && record.schema.format }}</template>
							</a-table-column>
							
							<a-table-column
								key="description"
								title="描述"
								data-index="description"
								:min-width="200"
								:width="220"
							/>
							<a-table-column key="debug" title="操作" :width="90">
								<template #default="{ record }">
									<a-tag								
								class="cursor-pointer mx-2 px-4 py-2"
								color="#40a9ff"
								@click="updateItemEvent(path, operation_method, operation,record)"
							>编辑</a-tag>
							<a-tag								
								class="cursor-pointer mx-2 px-4 py-2"
								color="#40a9ff"
								@click="delItemEvent(path, operation_method, operation,record)"
							>删除</a-tag>
								</template>
							</a-table-column>
						</a-table>						
					</div>
				</div>
			</div>
		</div>
	</div>

	<!--模             态            框  -->						  
<el-dialog
  ref="elDialog"
  :title="oper_sql.dialogStatus=='create' ? '创建' : '编辑'"
  v-model="oper_sql.dialogFormVisible"
  >
  <el-form
	ref="dataForm"
	:rules="oper_sql.rules"
	:model="oper_sql.tempArticleModel"
	label-position="left"
	label-width="100px"
	style="width: 450px;"
  >
  	<el-form-item
	  label="一级类目"
	  prop="importance"	  
	>
	  <el-input :disabled="oper_sql.yijileimu=='d' ? true:false" v-model="oper_sql.tempArticleModel.importance" placeholder="请输入类别，如‘指挥所土建工程’、‘设备设施管理’" />
	</el-form-item>
	<el-form-item
	  label="对象名称"
	  prop="title"	  
	>
	  <el-input :disabled="oper_sql.erjileimu=='d' ? true:false" v-model="oper_sql.tempArticleModel.title" placeholder="请输入该类别下的具体建筑、物资名称" />
	</el-form-item>
	
	<el-form-item
	  label="事件名称"
	  prop="abstractContent"
	>
	  <el-input v-model="oper_sql.tempArticleModel.abstractContent" placeholder="请输入事件名称，如‘建成’‘采购’‘维修’" />
	</el-form-item>

	<el-form-item
          label="日期时间"
          prop="timestamp"
        >
          <el-date-picker
            v-model="oper_sql.tempArticleModel.timestamp"
            type="datetime"
            placeholder="添加时间"
          />
    </el-form-item>
	
	<el-form-item
	  label="联系人"
	  prop="author"
	>
	  <el-input
		v-model="oper_sql.tempArticleModel.author"            
		placeholder="填写"
	  />
	</el-form-item>
 
	<el-form-item
	  label="电话"
	  prop="reviewer"
	>
	  <el-input
		v-model="oper_sql.tempArticleModel.reviewer"            
		placeholder="填写"
	  />
	</el-form-item>



	<el-form-item label="状态" prop="status">
	  <el-select
		v-model="oper_sql.tempArticleModel.status"
		class="filter-item"
		placeholder="请选择"
	  >
		<el-option
		  v-for="item in oper_sql.statusOptions"
		  :key="item"
		  :label="item"
		  :value="item"
		/>
	  </el-select>
	</el-form-item>
   
	<el-form-item
	  label=" 关联档案"
	  prop="pageviews"
	>
	  <el-input v-model="oper_sql.tempArticleModel.pageviews" />
	</el-form-item>
	
	<el-form-item label="描述" prop="fullContent">
	  <el-input
		v-model="oper_sql.tempArticleModel.fullContent"
		:autosize="{minRows: 2, maxRows: 4}"
		type="textarea"
		placeholder=" 信息"
	  />
	</el-form-item>
  </el-form>
  
  <div class="dialog-footer">
	<el-button @click="oper_sql.dialogFormVisible = false">
	  取 消
	</el-button>
	<el-button
	  type="primary"
	  @click="oper_sql.dialogStatus === 'create' ? createData() : updateData()"
	>
	  确 认
	</el-button>			       
  </div>
</el-dialog>
</template>
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, reactive } from "vue";
import clipboard from "clipboard";
import axios from 'axios'
import { cloneDeep } from 'lodash'

//import { message } from 'ant-design-vue'

import { strFirstToUpper } from '/@/views/wiki/libs/tools'

import { Tag } from '/@/views/dangAn/constants/app'
import { Swagger } from '/@/views/dangAn/constants/swagger'

import { GlobalParam } from '/@/views/dangAn/constants/app'

import { ElMessage, ElMessageBox, ElForm } from 'element-plus';
import {  
  createArticle,
  deleteArticleByName,
  deleteArticle,
  deleteArticleByImportanceAndTitle,
  updateArticle,
  defaultArticleModel,
  ArticleType,
  getArticles
} from '/@/request/articles'

interface Operation extends Swagger.Operation3 { }

const props = withDefaults(defineProps<{
	tags: Tag[]
	loading?: boolean
	server?: null | Swagger.Server
	globalParams?: GlobalParam[]
}>(), {
	tags: () => [],
	loading: false,
	server: () => null,
	globalParams: () => []
})

const emit = defineEmits(['get-listdata']);

// 当前激活效果
const current_active_path = ref('');

const dataForm = ref(ElForm);

const oper_sql =reactive({
	
	tempArticleModel: defaultArticleModel,
	dialogFormVisible: false,
	dialogStatus:'',
	
	rules: {
			importance: [
			  { required: true, message: '类目 is required', trigger: 'blur' }
			],
			title: [
			  { required: true, message: '对象 is required', trigger: 'change' }
			],
			abstractContent: [
			  { required: true, message: '事件 is required', trigger: 'blur' }
			],
			timestamp: [
			  { required: true, message: '时间 is required', trigger: 'change' }
			],
		  },
	statusOptions:['良好','故障'],
	pagedata:{
		currentPage: 1,
    	pageCount: 1000,
	},
	yijileimu:'',
	erjileimu:'',
	getTblData:{},
})

const delItemTag = (operation) =>{
	console.log(operation);
	ElMessageBox.confirm(`此操作删除 ’${operation.summary}‘，是否继续?`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          //confirmDeleteFile(fileInfo, true)
          await deleteArticleByImportanceAndTitle(operation.tags[0],operation.summary,ArticleType.SBDA).then(async()=>{
          	await getListData();
          });
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除'
          })
        })      
}

const resetTempArticleModel = (name)=> {
	oper_sql.tempArticleModel = cloneDeep(defaultArticleModel);
	oper_sql.tempArticleModel.importance=name;
	oper_sql.dialogStatus = 'create';
};

const addItemTag = async(tag) =>{
	console.log('OPERATION:::::::::',tag);
	resetTempArticleModel(tag.name);
	oper_sql.yijileimu='d';
	oper_sql.erjileimu='';
	oper_sql.dialogFormVisible=true;
}

const addGenTag = async() =>{
	console.log('addGenTag:::::::::');
	resetTempArticleModel('');
	let ArticleModel=oper_sql.tempArticleModel;
	oper_sql.yijileimu=oper_sql.erjileimu='';	
    oper_sql.dialogFormVisible=true;
}

// 滚动到指定Path
const scrollToPath = (path: string, offset: number = 0, smooth: boolean = false) => {
	let find = Array.from(
		document.getElementsByClassName("operation-item")
	).find(it => (it as any).dataset.path == path);
	if (find) {		
		current_active_path.value = path;
		return find.offsetTop+offset;
	}
	else return 0;
}
/**
 * 滚动到指定Tag
 * @param tagName Tag名
 * @param offset 上下偏移量
 * @param smooth 是否平滑
 */
const scrollToTag = (tagName: string, offset: number = 0, smooth: boolean = false) => {
	let find = Array.from(
		document.getElementsByClassName("tag-title")
	).find(it => (it as any).dataset.tagName == tagName);
	if (find) {
		window.scrollTo({
			top: (find as any).offsetTop + offset,
			behavior: smooth ? "smooth" : undefined
		});
	}
}

// 添加debug属性
const my_tags = ref<Tag[]>([]);
watch(() => props.tags, (tags) => {
	let result = cloneDeep(tags);
	result.forEach(tag => {
		Object.keys(tag.paths).forEach(path_name => {
			Object.keys(tag.paths[path_name]).forEach(opt_name => {
				tag.paths[path_name][opt_name].parameters.forEach(param => {
					param._debug_value = param.example;
				})
			})
		})
	})
	my_tags.value = result;
}, { immediate: true, deep: true })


const createData = async()=>{
	let ArticleModel=oper_sql.tempArticleModel;
	await createArticle(ArticleModel,ArticleType.SBDA).then(async() => {
        ElMessage.success('添加成功');
        oper_sql.dialogFormVisible=false;
        await getListData();
      }).catch(err => {
      ElMessage.warning('添加错误');
     });
} 

const updateData = async()=>{
	let ArticleModel=oper_sql.tempArticleModel;	
	await updateArticle(ArticleModel,ArticleType.SBDA).then(async()=>{
		await getListData();
		oper_sql.dialogFormVisible=false;
	}).catch(err => {
      ElMessage.warning('更新错误');
     });
}

const addItemEvent = (path, operation_method, operation)=>{
	console.log('1',path,'2',operation_method,'3',operation);
	
	resetTempArticleModel(operation.tags[0]);	
	oper_sql.tempArticleModel.title=operation.summary;	
	oper_sql.yijileimu='d';
	oper_sql.erjileimu='d';
	oper_sql.dialogFormVisible=true;
}

const delItemEvent = async(path, operation_method, operation,record)=>{
	console.log('1',path,'2',operation_method,'3',operation,'4',record);	
	console.log('delItemEvent',operation.tags[0],operation.summary,record.name);

	let idx=oper_sql.getTblData.total;
	let i=0;
	for (i=0;i<oper_sql.getTblData.total;i++){
		let ele=oper_sql.getTblData.data[i];
		if ((ele.importance==operation.tags[0])&&(ele.title==operation.summary)
			&&(ele.abstractContent==record.name)){
			idx=ele.id;
			break;
		}
	}
	if (i!=oper_sql.getTblData.total){
		await deleteArticle(idx,ArticleType.SBDA).then(async() => {
        ElMessage.success('删除成功');         
        await getListData();        
      }).catch(err => {
      ElMessage.warning('删除错误');
     });
	}
}

const updateItemEvent = (path, operation_method, operation,record)=>{
	console.log('1',path,'2',operation_method,'3',operation,'4',record);
	console.log('updateItemEvent');
	let idx=oper_sql.getTblData.total;
	let ele={};
	let i=0;
	for (i=0;i<oper_sql.getTblData.total;i++){
		ele=oper_sql.getTblData.data[i];
		if ((ele.importance==operation.tags[0])&&(ele.title==operation.summary)
			&&(ele.abstractContent==record.name)){
			idx=ele.id;
			break;
		}
	}
	console.log('---------------------'+idx);
	if (i!=oper_sql.getTblData.total){
		oper_sql.tempArticleModel=cloneDeep(ele);
		oper_sql.yijileimu='d';
		oper_sql.erjileimu='d';		
		oper_sql.dialogStatus = 'update';
		oper_sql.dialogFormVisible=true;	
	}
}

const getListData = async() =>{	
	oper_sql.getTblData={};
	await getArticles(oper_sql.pagedata,ArticleType.SBDA).then(res => {
		oper_sql.getTblData=res;
		emit('get-listdata',res);
	});
	
}

// 发起调试事件
const sendDebug = (path, method, path_data) => {
	if (!props.server) return message.error('请先选择环境')

	let url = `${props.server.url}${path}`

	let params = {};
	let headers = {};

	if (Array.isArray(props.globalParams)) {
		props.globalParams.forEach(p => {
			if (p.in == 'query') {
				params[p.name] = p.value;
			}
			else if (p.in == 'header') {
				headers[p.name] = p.value;
			}
		})
	}

	if (Array.isArray(path_data.parameters)) {
		path_data.parameters.forEach(p => {
			params[p.name] = p._debug_value;
		})
	}

	message.success('发起请求成功，详情参见Console或Network')
	axios({ url, method: 'post', params, headers }).then(res => {
		console.log('请求成功', res.data);
	}).catch(e => {
		console.log('请求失败', e);
	})
}

// 处理可点击复制的内容
let clips: clipboard[] = []; // 所有粘贴板实例，为了unmounted时销毁
onMounted(() => {
	const copyPath = new clipboard('.copy-path', {
		text: function (trigger) {
			return (trigger as any).dataset.path;
		}
	}).on('success', () => {
		message.success('Path已复制到粘贴板');
	})
	clips.push(copyPath)

	const copyParam = new clipboard('.copy-param', {
		text: function (trigger) {
			return (trigger as any).dataset.name;
		}
	}).on('success', () => {
		message.success('参数已复制到粘贴板');
	})
	clips.push(copyParam);
})
onUnmounted(() => {
	clips.forEach(clip => clip.destroy())
})

// 暴露方法
defineExpose({ scrollToTag, scrollToPath, addItemTag, addGenTag, getListData })

</script>
<style scoped lang="less">
.customWidth{
		    width:930px;
		}
		
.dangAncp-page-content {		
	.card {
		border-radius: 6px;
		padding: 10px 18px;
		margin: 12px 8px 12px;
		background: #fff;
	}
	.tag-box {
		.tag-title {
			background: #5c91b7;
			color: #f00;
			font-size: 18px;
			font-weight: 600;
		}
	}
	.api-box {
		.operation-item {
			&.active {
				box-shadow: 0 0 10px rgba(255, 0, 0, 0.6);
			}

			.title {
				font-size: 17px;
				font-weight: 600;
				margin-top: 6px;
			}
			.path {
				background: #eee;
				padding: 8px 16px;
				margin: 10px 0;
				border-radius: 2px;
				cursor: pointer;
			}
		}
	}
}
</style>
